import React, {Component} from 'react';
import axios from "axios";
import {Route} from "react-router-dom";
import Preview from "./Preview";

class Images extends Component {

    state = {
        loading: false,
        errorMsg: null,
        date: null,
        images: [],
        timer: null,
        index: 0
    }

    static getDerivedStateFromProps(props, state) {
        // 拦截index，如果index长度超过images的长度，就重置为0
        return {
            ...state,
            index: (state.index > state.images.length ? 0 : state.index)
        };
    }

    componentDidMount() {
        // 初始化加载图片
        this.onImages()
    }

    componentWillUnmount() {
        // 销毁定时器
        const {timer} = this.state
        if (timer) {
            clearInterval(timer)
        }
    }

    render() {
        const {images, loading, errorMsg, date} = this.state
        return (
            <div className={'images-container'}>
                <ul>
                    {
                        loading ? <p><img src={'/loading.gif'} alt={'loading'}/></p> :
                            errorMsg ? <p>{errorMsg}</p> :
                                images.map(item => {
                                    return (
                                        <li key={item.date}>
                                            <img
                                                className={date === item.date ? 'image-active' : ''}
                                                src={item.imgurl}
                                                alt={item.title}
                                                title={item.title}
                                                onClick={this.onPreviewImage(item)}
                                            />
                                        </li>
                                    )
                                })
                    }
                </ul>
                <hr/>

                {/*注册路由*/}
                <Route path={'/home/images/preview'} component={Preview}/>
            </div>
        );
    }

    // 加载图片数据
    onImages = () => {
        const data = {
            api_key: '531783566d5ccbe1',
            id: 'today',
            pn: 8
        };
        // 清空异常信息
        this.setState({errorMsg: null})
        // 开启加载中
        this.setState({loading: true})
        // 加载数据
        axios.get('/muxiaoguo-api/bing', {params: data}).then((res) => {
            const {data} = res
            if (parseInt(data.code) === 200) {
                this.setState({images: data.data})
                // 自动播放
                this.autoPlayImage()
            } else {
                this.setState({errorMsg: '请求异常：' + data.msg})
            }
        }).catch((err) => {
            this.setState({errorMsg: '服务器错误：' + err.message})
        }).finally(() => {
            // 关闭加载
            this.setState({loading: false})
        })
    }

    // 点击图片预览图片
    onPreviewImage = (image) => {
        return () => {
            if (image) {
                this.setState({date: image.date})
                // 编程式导航，replace替换，push正常
                this.props.history.replace({
                    pathname: '/home/images/preview',
                    state: image
                })
            }
        }
    }

    // 自动播放图片
    autoPlayImage = () => {
        const {images} = this.state
        const timer = setInterval(() => {
            this.setState({index: this.state.index + 1})
            this.onPreviewImage(images[this.state.index])()
        }, 5000)
        this.setState({timer})
    }

}

export default Images;
